/**
 * Created with IntelliJ IDEA.
 * User: osereda
 */
package com.google.code.bankagregator.core;

import com.google.code.bankagregator.dao.CreditDAO;
import com.google.code.bankagregator.dao.DepositDAO;
import com.google.code.bankagregator.entities.Credit;
import com.google.code.bankagregator.entities.Deposit;
import com.google.code.bankagregator.vo.CreditOffer;
import com.google.code.bankagregator.vo.DepositOffer;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Processing data received from the user interface.
 */
@Local
@Stateless
public class DataManager extends AggregatorLogger {

    @EJB
    CreditDAO creditDAO;
    @EJB
    DepositDAO depositDAO;

    /**
     * List of credit offers suitable for specified parameters
     *
     * @param criteria specified parameters
     * @return credit offer list or empty list if no compatible credits found.
     */
    public List<CreditOffer> getSuitableCreditOffers(Credit criteria) {
        List<Credit> creditList = creditDAO.getByCriteria(criteria);
        List<CreditOffer> offerList = new ArrayList<>();

        info("[CREDIT OFFERS SEARCH START] Criteria:" + criteria);

        if (!creditList.isEmpty()) {
            for (Credit item : creditList) {
                offerList.add(new CreditOffer(item, criteria));
            }
            Collections.sort(offerList);
        }
        info("[CREDIT OFFERS RESULT] count:" + offerList.size());
        return offerList;
    }

    public List<DepositOffer> getSuitableDepositOffers(Deposit criteria, int amount) {
        List<Deposit> depositList = depositDAO.getByAccurateCriteria(criteria, amount);
        List<DepositOffer> offerList = new ArrayList<>();

        if (!depositList.isEmpty()) {
            for (Deposit item : depositList) {
                offerList.add(new DepositOffer(item, amount));
                Collections.sort(offerList);
            }


        } else {
            List<Deposit> newDepositList = depositDAO.getByInaccurateCriteria(criteria, amount);
            for (Deposit item : newDepositList) {
                offerList.add(new DepositOffer(item, amount));
                Collections.sort(offerList);
            }
        }
        return offerList;
    }


    public List<Credit> getAllActiveCredits() {
        return creditDAO.getActive();
    }

    public List<Deposit> getAllActiveDeposits() {
        return depositDAO.getActive();
    }

}
